﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using RecipeSL;
using RecipeSL.RecipeServiceReference;
using Mathematics.RationalNumbers;
using RecipeProject.ViewModel;

namespace RecipeSL.ViewModel
{
    public class MainPageViewModel : ViewModelBase
    {
        #region Fields
        IServiceAgent _serviceAgent;
        ObservableCollection<Recipe> _recipes;
        Recipe _selecteRecipe;
        bool _recipeLoaderCalled;
        #endregion

        #region Constructors

        public MainPageViewModel() : this(new ServiceAgent()) { }
        public MainPageViewModel(IServiceAgent serviceAgent)
        {
            _serviceAgent = serviceAgent;
            _recipes = new ObservableCollection<Recipe>();
        }

        #endregion

        #region Properties

        public ObservableCollection<Recipe> AllRecipes
        {
            get
            {
                if (!_recipes.Any() && !_recipeLoaderCalled)
                {
                    _serviceAgent.GetRecipes(LoadRecipes);
                    _recipeLoaderCalled = true;
                }
                return _recipes;
            }
        }

        public Recipe SelectedRecipe
        {
            get { return _selecteRecipe; }
            set
            {
                if (value == _selecteRecipe)
                    return;
                _selecteRecipe = value;
                OnPropertyChanged("SelectedRecipe");
            }
        }


        #endregion

        #region Private Helpers
        
        private void LoadRecipes(object sender, RecipeServiceReference.GetRecipesCompletedEventArgs e)
        {
            foreach (var r in e.Result)
                _recipes.Add(r);
            OnPropertyChanged("AllRecipes");


        }

        #endregion

    }
}
